package org.senf.outerspace.galaxy;

import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.senf.outerspace.galaxy.view.GalaxyView;

public class GameClock {

	private static GameClock instance;
	
	private float frameStart;
	private float frameEnd;
	private float frameTime;
	private float fps;
	
	private Thread clockThread;
	private boolean running;
	
	private GalaxyView galaxyView;
	
	public static GameClock getInstance() {
		if (instance == null) {
			instance = new GameClock();
		}
		return instance;
	}

	private GameClock() {
		IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
		galaxyView = (GalaxyView)page.findView(GalaxyView.ID);
		
		final Runnable render = new Runnable() {
			@Override
			public void run() {
			   Galaxy.getInstance().updateGalaxy();
			   galaxyView.drawScene();
			}
		};
		
		Runnable clock = new Runnable() {
			@Override
			public void run() {
				frameStart = getTime();
				do {
				   do {
				      frameEnd = getTime();
				   } while(frameStart == frameEnd);

				   frameTime = frameEnd-frameStart;
				   frameStart = frameEnd;
				   fps = 1.0f/frameTime;
				   Display.getDefault().syncExec(render);
				} while(running);
			}
		};
		clockThread = new Thread(clock,"ClockThread");
	}
	
	public synchronized void start() {
		running = true;
		clockThread.start();
	}
	
	public synchronized void stop() {
		running = false;
	}
	
	public float getFps() {
		return fps;
	}
	
	public float getFrameTime() {
		return frameTime;
	}
	
	private float getTime() {
		return (float)System.nanoTime()/1000000000f;
	}
}
